package com.glela.common.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.glela.common.beans.AreaCommonBean;
import com.glela.common.constant.CommonConstants;
import com.glela.common.dao.IAreaDao;
import com.glela.common.mapper.AreaInfoMapper;

/**
 * 
 * IAreaDao 实现类
 * @author liujie
 *
 */
@Repository
public class AreaDaoImp implements IAreaDao{

	//区级mapper
	@Autowired
	private AreaInfoMapper areaMapper;

	@Override
	public List<AreaCommonBean> selectChildrenByFather(String fatherCode) {
		List<AreaCommonBean> childrenList = areaMapper.selectChildrenByFather(fatherCode);
		if(childrenList==null || childrenList.size()<=0){
			return  new ArrayList<>();
		} 
 		return childrenList;
	}

	@Override
	public  AreaCommonBean selectAreaByCode(String code) {
  		return areaMapper.selectAreaByCode(code);
	}

	@Override
	public  AreaCommonBean  selectAreaByName(String name) {
		name = name+"%";
		List<AreaCommonBean> list = areaMapper.selectAreaByName(name);
		if(list != null && list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public  AreaCommonBean  selectCountryByName(String name) {
		name = name+"%";
		List<AreaCommonBean> list = areaMapper.selectCountryByName(name);
		if(list != null && list.size()>0){
			return list.get(0);
		}
		return null;
	}
 
	 
	@Override
	public List<AreaCommonBean> loadAllChildrenByFather(String fatherCode) {
		List<AreaCommonBean> childList = selectChildrenByFather(fatherCode);
 		for(AreaCommonBean bean:childList){
  			getChildrenByCode(bean);
 		}
		return childList;
	}

	/**
	 * 根据父节点 获取 子节点
	 * 递归
	 * @param bean
	 * @return
	 */
	private AreaCommonBean getChildrenByCode(AreaCommonBean bean){
		String code = bean.getCode();
		int hasChild = bean.getHasChildren();
		if(hasChild == CommonConstants.HAS_CHILDREN){
			List<AreaCommonBean> tmpList =  selectChildrenByFather(code);
			if(tmpList !=null && tmpList.size() > 0){
				for(AreaCommonBean tmp:tmpList){
	 				getChildrenByCode(tmp);
				} 
			}else{
				tmpList = new ArrayList<>();
			}
  			bean.setChildrenList(tmpList);
 		}else{
 			bean.setChildrenList(new ArrayList<AreaCommonBean>());
			return bean;
		}
		return bean;
	}
}
